package com.caifu.util;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DES {
	private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
	private static String caifuDESKey = "19920308";
//	private static String caifuDESKey = "abcdefgh";

	/**
	 * 加密
	 * @param encryptString
	 * @param encryptKey
	 * @return
	 * @throws Exception
	 */
	public static String encryptDES(String encryptString) throws Exception {
		IvParameterSpec zeroIv = new IvParameterSpec(iv);

		SecretKeySpec key = new SecretKeySpec(caifuDESKey.getBytes(), "DES");

		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

		cipher.init(Cipher.ENCRYPT_MODE, key, zeroIv);

		byte[] encryptedData = cipher.doFinal(encryptString.getBytes());

		return Base64.encode(encryptedData);

	} 

	/**
	 * 解密
	 * @param decryptString
	 * @param decryptKey
	 * @return
	 * @throws Exception
	 */
	public static String decryptDES(String decryptString) throws Exception {
		byte[] byteMi = Base64.decode(decryptString);

		IvParameterSpec zeroIv = new IvParameterSpec(iv);

		SecretKeySpec key = new SecretKeySpec(caifuDESKey.getBytes(), "DES");

	 	Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");

	 	cipher.init(Cipher.DECRYPT_MODE, key, zeroIv);

		byte decryptedData[] = cipher.doFinal(byteMi);

		return new String(decryptedData);

	}
	
	public static String parseByte2HexStr(byte buf[]) {  

		StringBuffer sb = new StringBuffer();  

		for (int i = 0; i < buf.length; i++) {  

			String hex = Integer.toHexString(buf[i] & 0xFF);  

			if (hex.length() == 1) {  

				hex = '0' + hex;  

			}  

			sb.append(hex.toUpperCase());  

		}  

		return sb.toString();  

	}

	
	public static void main(String[] arge) {
		String plaintext = "111111";
		try {
			String ciphertext = DES.encryptDES(plaintext);

			System.out.println("明文：" + plaintext);

			System.out.println("密钥：" + caifuDESKey);

			System.out.println("密文：" + ciphertext);

			System.out.println("解密后：" + DES.decryptDES("8+A5i6aAhPBQb3gcFMb1sg=="));
		} catch(Exception e) {
			
		}
	}
	
}
